from .Read import read
from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine, async_sessionmaker
from sqlalchemy.ext.asyncio.session import AsyncSession
import typing as T
from fastapi import Depends
from pathlib import Path


ROOT_DIR = Path(__file__).parent.parent


def createEngine(configuration: dict):
    datasource: dict = configuration["fastapi"]["datasource"]
    uri = f'{datasource["dataname"]}+{datasource["driver"]}://{datasource["username"]}:{datasource["password"]}@{datasource["url"]}'
    return create_async_engine(
        uri,
        pool_size=20,
        echo=datasource["echo"],
        max_overflow=50,
        pool_recycle=3600,
        pool_pre_ping=True,
    )


configuration: dict = read()


engine: AsyncEngine = createEngine(configuration)

SessionFactory = async_sessionmaker(engine)


async def getSession():
    async with SessionFactory() as session:
        async with session.begin():
            yield session


Session = T.Annotated[AsyncSession, Depends(getSession)]

AopMap: T.Dict[T.Callable, T.Tuple[str, str, str]] = {}
